package com.music.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;

public class ChangeCharset {

	/** 8 位 UTF转换格式 */
	public static final String UTF_8 = "UTF-8";
	/** 中文超大字符集 **/
	public static final String GBK = "GBK";
	/** 16 位 UTF转换格式，Big Endian(最低地址存放高位字节）字节顺序 */
	public static final String UTF_16BE = "UTF-16BE";

	/** 将字符编码转换成UTF-8 */
	public static String toUTF_8(String str)
			throws UnsupportedEncodingException {
		return changeCharset(str, UTF_8);
	}

	/** 将字符编码转换成UTF-16BE */
	public static String toUTF_16BE(String str) {
		return changeCharset(str, UTF_16BE);
	}

	/*
	 * 字符串编码转换的实现方法
	 * 
	 * @param str 待转换的字符串
	 * 
	 * @param newCharset 目标编码
	 */
	public static String changeCharset(String str, String newCharset) {
		try {
			if (str != null) {
				// 用默认字符编码解码字符串。与系统相关，中文默认为GBK
				byte[] bs = str.getBytes();
				return new String(bs, newCharset);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 用新的字符编码生成字符串
		return "";
	}

	/**
	 * 
	 * 字符串编码转换的实现方法
	 * 
	 * @param str
	 *            待转换的字符串
	 * @param oldCharset
	 *            源字符集
	 * @param newCharset
	 *            目标字符集
	 */
	public static String changeCharset(String str, String oldCharset,
			String newCharset) {
		try {
			if (str != null) {
				// 用源字符编码解码字符串
				byte[] bs = str.getBytes(oldCharset);
				return new String(bs, newCharset);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";

	}

	public static String ChangeString(String str) {
		try {
			String utf16be = toUTF_16BE(str);
			return changeCharset(utf16be, UTF_16BE, GBK);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";

	}

	public static String codeString(File file) throws Exception {
		BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
				file));
		int p = (bin.read() << 8) + bin.read();
		String code = null;
		switch (p) {
		case 0xefbb:
			code = "UTF-8";
			break;
		case 0xfffe:
			code = "Unicode";
			break;
		case 0xfeff:
			code = "UTF-16BE";
			break;
		default:
			code = "GBK";
		}

		return code;
	}
}
